import React, { useCallback, useEffect, useState } from 'react';
import { Button, Input, Space, Table, Modal, message } from 'antd';
import type { GetProps } from 'antd';
import http from '../api/http';
import Column from 'antd/lib/table/Column';
import type { PaginationProps, TableProps } from 'antd';
import { DeleteOutlined, ExclamationCircleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Edit } from './edit'; // 假设edit组件已适配healthplan
type SearchProps = GetProps<typeof Input.Search>;
import { Divider, Flex, Tag } from 'antd';
import { Add } from "./add"; // 假设add组件已适配healthplan
const { Search } = Input;
const { confirm } = Modal;
import type { IHealthPlan } from '../types/healthplan'; // 健康计划类型定义

export default function HealthPlan() {
    const [name, setName] = useState('');
    const [data, setData] = useState<IHealthPlan[]>([]);
    const [pagination, setPagination] = useState({
        page: 1,
        size: 3,
        total: 0
    });
    // 用于记录选中的行ID
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

    const search = useCallback(() => {
        // 调用健康计划分页接口
        http.getList<IHealthPlan>("healthplan/page", {
            page: pagination.page,
            size: pagination.size,
            name: name // 按健康计划名称搜索
        }).then(res => {
            setData(res.data || []);
            setPagination(n => ({
                ...n,
                page: res.page || n.page,
                total: res.count || 0  
            }));
        }).catch(err => {
            console.error('获取健康计划数据失败:', err);
        });
    }, [pagination.page, pagination.size, name]);

    useEffect(() => {
        search();
    }, [name, search]);

    const onSearch: SearchProps['onSearch'] = (value) => {
        setName(value);
        setPagination(prev => ({ ...prev, page: 1 }));
    };

    const selectOnChange: PaginationProps['onChange'] = (page, size) => {
        setPagination({ page: page, size: size, total: pagination.total });
    };

    // 处理单行删除
    const handleDelete = (id: number) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这条健康计划记录吗？此操作不可撤销。',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                // 调用健康计划删除接口
                http.delete("healthplan", { id: id })
                    .then(() => {
                        message.success('删除成功');
                        search();
                        setSelectedRowKeys([]);
                    })
                    .catch(err => {
                        console.error('删除失败:', err);
                        message.error('删除失败');
                    });
            }
        });
    };

    // 处理批量删除
    const handleBatchDelete = () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请先选择要删除的记录');
            return;
        }

        confirm({
            title: '批量删除',
            icon: <ExclamationCircleOutlined />,
            content: `确定要删除选中的 ${selectedRowKeys.length} 条健康计划记录吗？此操作不可撤销。`,
            okText: '确认',
            cancelText: '取消',
            onOk() {
                // 调用健康计划批量删除接口
                http.deleteBatch('healthplan/dels', selectedRowKeys)
                    .then(() => {
                        message.success('批量删除成功');
                        search();
                        setSelectedRowKeys([]);
                    })
                    .catch(err => {
                        console.error('批量删除失败:', err);
                        message.error('批量删除失败');
                    });
            }
        });
    };

    // 行选择配置
    const rowSelection: TableProps<IHealthPlan>['rowSelection'] = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys) => {
            setSelectedRowKeys(newSelectedRowKeys);
        },
    };

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [currentEditData, setCurrentEditData] = useState<IHealthPlan | undefined>();

    const showModal = () => {
        setIsModalOpen(true);
    };

    const editShowModal = (record: IHealthPlan) => {
        setCurrentEditData(record);
        setEditModalOpen(true);
    };

    const editHandleCancel = () => {
        setEditModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    return (
        <>
            <Space style={{ marginBottom: 16 }}>
                <Search
                    placeholder="请输入健康计划名称"
                    onSearch={onSearch}
                    style={{ width: 200 }}
                    allowClear
                />
                <Button type="primary" onClick={showModal}>添加</Button>
                <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={handleBatchDelete}
                    disabled={selectedRowKeys.length === 0}
                >
                    批量删除
                </Button>
            </Space>

            <Table<IHealthPlan>
                dataSource={data}
                rowKey="id"
                pagination={{
                    current: pagination.page,
                    pageSize: pagination.size,
                    total: pagination.total,
                    showQuickJumper: true,
                    showTotal: (total) => '共有' + total + '条数据',
                    pageSizeOptions: ['3', '5', '8'],
                    showSizeChanger: true,
                    onChange: selectOnChange,
                    align: 'center'
                }}
                rowSelection={rowSelection}
            >
                <Column title="编号" dataIndex="id" key="id" />
                <Column title="计划编码" dataIndex="code" key="code" />
                <Column title="计划名称" dataIndex="name" key="name" />
                <Column title="适用人群" dataIndex="crowd" key="crowd" />
                <Column 
                    title="计划类型" 
                    dataIndex="type" 
                    key="type" 
                    render={(type) => {
                        switch(type) {
                            case '基础保健': return <Tag color="green">{type}</Tag>;
                            case '疾病康复': return <Tag color="blue">{type}</Tag>;
                            case '专项训练': return <Tag color="purple">{type}</Tag>;
                            default: return type;
                        }
                    }} 
                />
                <Column title="计划周期(天)" dataIndex="cycle" key="cycle" />
                <Column title="每日时长(分钟)" dataIndex="dailyDuration" key="dailyDuration" />
                <Column 
                    title="是否需要医生指导" 
                    dataIndex="needDoctor" 
                    key="needDoctor" 
                    render={(val) => val === 1 ? 
                        <Tag icon={<CheckCircleOutlined />} color="success">是</Tag> : 
                        <Tag icon={<CloseCircleOutlined />} color="error">否</Tag>
                    } 
                />
                <Column 
                    title="适用性别" 
                    dataIndex="gender" 
                    key="gender" 
                    render={(val) => {
                        switch(val) {
                            case 0: return '男';
                            case 1: return '女';
                            case 2: return '通用';
                            default: return '未知';
                        }
                    }} 
                />
                <Column title="最小适用年龄" dataIndex="minAge" key="minAge" />
                <Column title="最大适用年龄" dataIndex="maxAge" key="maxAge" />
                <Column title="计划概述" dataIndex="overview" key="overview" width={200} />
                <Column title="注意事项" dataIndex="notes" key="notes" width={200} />
                <Column title="创建时间" dataIndex="createtime" key="createtime" />
                <Column title="更新时间" dataIndex="updatetime" key="updatetime" />
                <Column
                    title="操作"
                    key="action"
                    render={(_, record: IHealthPlan) => (
                        <Space size="middle">
                            <Button
                                type="primary"
                                size="small"
                                onClick={() => editShowModal(record)}
                            >
                                编辑
                            </Button>
                            <Button
                                danger
                                size="small"
                                onClick={() => handleDelete(record.id)}
                            >
                                删除
                            </Button>
                        </Space>
                    )}
                />
            </Table>
            {/* 传递健康计划相关的props到添加组件 */}
            <Add 
                onSuccess={search} 
                isModalOpen={isModalOpen} 
                handleCancel={handleCancel}
            />
            {/* 传递健康计划相关的props到编辑组件 */}
            <Edit 
                onSuccess={search} 
                EditModalOpen={editModalOpen} 
                EditHandleCancel={editHandleCancel} 
                editData={currentEditData}
            />
        </>
    );
}